package com.jfm.jfmc.core.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jfm.jfmc.core.constants.MonitorMetricsSQL;
import com.jfm.jfmc.core.entity.modle.MonitorMetrics;
import com.jfm.jfmc.core.mapper.MonitorMetricsMapper;
import com.jfm.jfmc.core.service.IMonitorMetricsService;
import com.jfm.jfmm.collector.entity.collect.CollectResult;
import com.jfm.jfmm.collector.entity.collect.Result;
import com.jfm.jfmm.collector.enums.AlarmStatus;
import com.jfm.jfmm.utils.SHA256Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author DYang
 * @since 2024-11-07 22:31
 */
@Service
public class MonitorMetricsServiceImpl extends ServiceImpl<MonitorMetricsMapper,MonitorMetrics> implements IMonitorMetricsService {

    // 缓存子表名
    private static Map<String,String> childTableMap = new ConcurrentHashMap<>();

    @Autowired
    private MonitorMetricsMapper monitorMetricsMapper;

    @Async
    @Override
    public void store(CollectResult collectResult) {
        Result result = collectResult.getResult();

        Map<String, Object> valueMap = result.getValue();
        if (valueMap == null) {
            return;
        }
        String deviceCode = result.getDeviceCode();
        String tableName = "monitor" + "_" + result.getDeviceCode();
        List<MonitorMetrics> monitors = new ArrayList<>();
        // 新增数据
        for (Map.Entry<String, Object> entry : valueMap.entrySet()) {
            String collectCode = entry.getKey();
            Object data = entry.getValue();
            float value;
            if (data instanceof String) {
                value = 1;
            }else {
                value = Float.parseFloat(data.toString());
            }

            MonitorMetrics info = new MonitorMetrics();
            info.setTs(new Timestamp(collectResult.getStartTime()));
            info.setAlarm(AlarmStatus.ALARM_STATUS_NORMAL.getCode());
            info.setResponseTime(collectResult.getResponseTime());
            info.setMetricCode(result.getMetricCode());
            info.setCollectCode(collectCode);
            info.setData(value);
            monitors.add(info);

//            String childTable = this.buildTableName(result,collectCode);
//            String[] tags = this.buildTags(collectCode, data, result);
//            if (data instanceof String) {
//                data = 1;
//            }
//
//            String sql = MonitorMetricsSQL.getChildTableSql(
//                    childTable,
//                    tags,
//                    collectResult.getStartTime(),
//                    collectResult.getResponseTime(),
//                    data,
//                    AlarmStatus.ALARM_STATUS_NORMAL.getCode()
//            );
//           // 执行SQL,存储数据
//            monitorMetricsMapper.executeSql(sql);
        }
        monitorMetricsMapper.batchInsert(tableName,deviceCode,monitors);
    }

    /**
     * 创建标签
     */
    private String[] buildTags(String collectCode,Object data, Result result) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("code", collectCode);
        jsonObject.set("data", data);

        return new String[] {
                result.getDeviceCode(),
                result.getMetricCode(),
                result.getUnit(),
                collectCode,
                jsonObject.toString()
        };
    }

    /**
     * 构建表名
     * @param result
     * @return
     */
    private String buildTableName(Result result,String collectCode) {
        String key = result.getDeviceCode() + "_" + result.getMetricCode() + "_" + collectCode;
        String val = childTableMap.get(key);
        if (val == null) {
            val = result.getDeviceCode() + "_" + result.getMetricCode() + "_" + SHA256Util.getSHA256Str(collectCode, 2);
            childTableMap.put(key,val);
        }
        return val;
    }
}
